//
//  HouseDetailView.m
//  ThuePhongDep
//
//  Created by Huynh Chi Hung on 8/1/13.
//  Copyright (c) 2013 Huynh Chi Hung. All rights reserved.
//

#import "HouseDetailView.h"
#import "UIImageView+WebCache.h"
#import "Define.h"
#import "AppViewController.h"
#import "SBJSON.h"

@implementation HouseDetailView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        CGFloat colors[8] = {
            0, 0, 0, 0.5,
            0, 0, 0, 0.5
        };
        // Initialization code
        self.margin = UIEdgeInsetsMake(15, 12, 10, 12);
        
        [[self titleBar] setColorComponents:colors];
        self.contentColor = [UIColor colorWithWhite:0.0 alpha:0.8];
        
        // The gradient style (Linear, linear reversed, radial, radial reversed, center highlight). Default = UAGradientBackgroundStyleLinear
        [[self titleBar] setGradientStyle:UAGradientBackgroundStyleLinear];
        
        // The line mode of the gradient view (top, bottom, both, none). Top is a white line, bottom is a black line.
        //        [[self titleBar] setLineMode: pow(2, (arc4random() % 3))];
        
        // The noise layer opacity. Default = 0.4
        //        [[self titleBar] setNoiseOpacity:0.4];
        
        // The header label, a UILabel with the same frame as the titleBar
        [self headerLabel].font = [UIFont boldSystemFontOfSize:floor(self.titleBarHeight / 2.0)];
        
        _APIRequester = [APIRequester new];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame title:(NSString*)title houseID:(NSString *)houseID {
    self = [self initWithFrame:frame];
    if (self) {
        self.headerLabel.text = title;
        _houseID = houseID;
        _pageImageView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _pageImageView.pagingEnabled = YES;
        _pageImageView.delegate = self;
        _pageImageView.hidden = YES;
        [self.contentView addSubview:_pageImageView];
        
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
        [self.contentView addSubview:_pageControl];
        _pageControl.hidden = YES;
        _pageControl.numberOfPages = 1;
        [_pageControl setCurrentPage:0];
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundView = nil;
        _tableView.hidden = YES;
        [self.contentView addSubview:_tableView];
        
        
        [self requestWithhouseID:_houseID];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [_pageImageView setFrame:CGRectMake(0, 0,self.contentView.bounds.size.width, self.contentView.bounds.size.width*2/3)];
    [_pageControl setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 2,self.contentView.bounds.size.width, 5)];
    [_tableView setFrame:CGRectMake(0, self.contentView.bounds.size.width*2/3 + 10, self.contentView.bounds.size.width, self.contentView.bounds.size.height - self.contentView.bounds.size.width*2/3 - 13)];
}

-(void)requestWithhouseID:(NSString *)houseID
{
    NSString *requestURL = STRING_REQUEST_URL_PHONGDEP_GET_HOUSE_DETAIL(houseID);
    [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_PHONGDEP_GET_HOUSE_DETAIL andRootURL:requestURL andPostMethodKind:YES andParams:nil andDelegate:self];
    
//#ifdef __DEBUG__
//    NSLog(@"requestTheNext: %@", requestURL);
//#endif
}

- (void)loadInterface {
    _pageImageView.hidden = NO;
    _pageControl.hidden = NO;
    _tableView.hidden = NO;
    [_tableView reloadData];
}

/*
 if data is successfully received, this method will be called by connection
 */

- (void)requestWithType:(ENUM_API_REQUEST_TYPE)requestType {
    // USER ID
    NSString *userID = @"";
    
    // USER NAME
    NSString *userName = @"";
    
    // DEVICE UDID
    NSString *deviceUDID = [UIDevice currentDevice].deviceUDID;
    [UserDataManager Shared].userDeviceUDID = deviceUDID;
    
    
    // DEVICE TOKEN
    NSString *deviceToken = @"";
    if ([UserDataManager Shared].userRegisteredDeviceToken) {
        deviceToken = [UserDataManager Shared].userRegisteredDeviceToken;
        [UserDataManager Shared].userDeviceToken = [UserDataManager Shared].userRegisteredDeviceToken;
    }
    
    // ENTER FOREGROUND APP
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:deviceToken forKey:STRING_REQUEST_KEY_DEVICE_TOKEN];
    [params setValue:deviceUDID forKey:STRING_REQUEST_KEY_DEVICE_UDID];
    [params setValue:userID forKey:STRING_REQUEST_KEY_USER_ID];
    [params setValue:userName forKey:STRING_REQUEST_KEY_USER_NAME];
    [params setValue:[NSString stringWithFormat:@"%i", [UIDevice currentDevice].platformType] forKey:STRING_REQUEST_KEY_DEVICE_TYPE];
    [params setValue:[UIDevice currentDevice].platformString forKey:STRING_REQUEST_KEY_DEVICE_NAME];
    
    switch (requestType) {
        case ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_01: {
            [params setValue:_contactNumber forKey:STRING_REQUEST_KEY_PHONE_FROM_NUMBER];
            [params setValue:_contactNumber forKey:STRING_REQUEST_KEY_PHONE_TO_NUMBER];
            
#ifdef __DEBUG__
            NSLog(@"CALL PHONE 01: %@", params);
#endif
            [_APIRequester requestWithType:requestType andRootURL:STRING_REQUEST_URL_ACTIONS_CALL_PHONE_01 andPostMethodKind:YES andParams:params andDelegate:self];
            
            // TODO:
            NSString *phoneNumber = [@"tel://" stringByAppendingString:_contactNumber];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
            break;
        }
    
        default:
            break;
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
//#ifdef __DEBUG__
//    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
#ifdef __DEBUG__
#else
        if (type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        }
#endif
        return;
    }
    
    NSMutableDictionary *jsonData = [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_DATA];
    
    if (!jsonData || jsonData.count == 0) {
        return;
    }
    
    _jsonDataRecieved = jsonData;
    
    if (type == ENUM_API_REQUEST_TYPE_PHONGDEP_GET_HOUSE_DETAIL) {
        NSArray *imageArray = [NSArray arrayWithObject:[jsonData objectForKey:@"image"]];
        int totalImage =  [imageArray count];
        _pageControl.numberOfPages = totalImage;
        [_pageControl setCurrentPage:0];
        _pageImageView.contentSize = CGSizeMake(_pageImageView.frame.size.width*totalImage, _pageImageView.frame.size.height);
        
        int i = 0;
        for (NSString *imageURL in imageArray) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_pageImageView.frame.size.width*i + 5, 0,
                                                                                   _pageImageView.frame.size.width -10, _pageImageView.frame.size.height- 8)];
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            [_pageImageView addSubview:imageView];
            [imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:IMG_AVARTAR_DUMMY];
            
            i++;
        }
    
        // LOAD INTERFACE
        [self loadInterface];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
//#ifdef __DEBUG__
//    NSLog(@"requestFailed %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable] && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

#pragma mark - TableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        if (indexPath.row == 0)
            return 60;
        else if (indexPath.row == 0) return 60;
    }
    return 40;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, headerView.frame.size.width-20, 40)];
    static NSString* boldFontName = @"Avenir-Black";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:boldFontName size:16];
    label.backgroundColor = [UIColor clearColor];
    if (section  == 0) {
        label.text = @"Thông tin Nhà";
    }
    else if (section == 1) {
        label.text = @"Thông tin liên hệ";
    }
    [headerView addSubview:label];
    return  headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}


- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section  == 0) {
        return 5; // address, parking, free, description
    }
    else if (section == 1) {
        return 3; // name, phone, email
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSString *cellIdentifier = @"UAModalPanelCell";
    //    static NSString* fontName = @"Avenir";
    static NSString* boldFontName = @"Avenir-Black";
    
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
        cell.textLabel.font = [UIFont fontWithName:boldFontName size:14];
        cell.textLabel.numberOfLines = 3;
	}
    int section = indexPath.section;
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.groupingSeparator = @".";
    numberFormatter.decimalSeparator = @",";
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    
	if (section  == 0) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            NSString *address = [_jsonDataRecieved objectForKey:@"address"];
            NSString *district = [_jsonDataRecieved objectForKey:@"district"];
            NSString *city = [_jsonDataRecieved objectForKey:@"city"];
            cell.textLabel.text = [NSString stringWithFormat:@"Địa chỉ: %@, Quận %@, Tỉnh/TP %@.",address,district,city];            
        }
        else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"Chỗ để xe: %@",
                                   [_jsonDataRecieved objectForKey:@"parking"]];
        }
        else if (indexPath.row == 2) {
            cell.textLabel.text = [NSString stringWithFormat:@"Phòng trống: %@/%@",
                                   [_jsonDataRecieved objectForKey:@"free_rooms"],[_jsonDataRecieved objectForKey:@"total_rooms"]];            
        }        
        else if (indexPath.row == 3) {
            NSString *tmp = @"";
            id object = [_jsonDataRecieved objectForKey:@"features"];
            if ([object isKindOfClass:[NSDictionary class]]) {
                NSDictionary *features = (NSDictionary*) object;
                for (id key in [features allKeys]) {
                    NSDictionary *dicTmp = [features objectForKey:key];
                    tmp = [tmp stringByAppendingFormat:@",%@",[dicTmp objectForKey:@"name"]];
                }
                cell.textLabel.text = [NSString stringWithFormat:@"Tiện ích chung: %@",tmp];
            }
            else {
                cell.textLabel.text = [NSString stringWithFormat:@"Tiện ích chung:"];
            }
        }
        else if (indexPath.row == 4) {
            if ([_jsonDataRecieved objectForKey:@"description"] != [NSNull null])
                cell.textLabel.text = [NSString stringWithFormat:@"Mô tả: %@",[_jsonDataRecieved objectForKey:@"description"]];
            cell.textLabel.text = @"Mô tả:";
        }
    }
    else if (section == 1) {
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        NSDictionary *contactInfo = [_jsonDataRecieved objectForKey:@"contact"];
        
        if (indexPath.row == 0) {
            cell.textLabel.text = [NSString stringWithFormat:@"Tên: %@",
                                   [contactInfo objectForKey:@"name"]];
        }
        else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"Phone: %@",
                                   [contactInfo objectForKey:@"phone"]];
        }
        else if (indexPath.row == 2) {
            cell.textLabel.text = [NSString stringWithFormat:@"Email: %@",
                                   [contactInfo objectForKey:@"email"]];
        }
    }
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *contactInfo = [_jsonDataRecieved objectForKey:@"contact"];
        if (indexPath.row == 1) {
            // Call action
//            NSString *phoneNumber = [@"tel://" stringByAppendingString:[contactInfo objectForKey:@"phone"]];
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
            
            _contactNumber = [contactInfo objectForKey:@"phone"];
            ALERT_2(_contactNumber, @"", self, @"Cancel", @"Call");
        }
        else if (indexPath.row == 2) {
            // Email action
            [[AppViewController Shared] changeToFeedbackVCWithEmailAddress:[contactInfo objectForKey:@"email"]];

        }
    }
}

#pragma scroolViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    if (sender == _pageImageView) {
        CGFloat pageWidth = _pageImageView.frame.size.width;
        int page = floor((_pageImageView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        _pageControl.currentPage = page;
    }
}

#pragma mark - ALERT

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self requestWithType:ENUM_API_REQUEST_TYPE_ACTIONS_CALL_PHONE_01];
    }
}

@end
